Custom Exception

Course- Java >

If you are creating your own Exception that is known as custom exception or user-defined exception. Java custom exceptions are used to customize the exception according to user need.

By the help of custom exception, you can have your own exception and message.

Let's see a simple example of java custom exception.

 
  1. class InvalidAgeException extends Exception{  
  2.  InvalidAgeException(String s){  
  3.   super(s);  
  4.  }  
  5. }  
 
  1. class TestCustomException1{  
  2.   
  3.    static void validate(int age)throws InvalidAgeException{  
  4.      if(age<18)  
  5.       throw new InvalidAgeException("not valid");  
  6.      else  
  7.       System.out.println("welcome to vote");  
  8.    }  
  9.      
  10.    public static void main(String args[]){  
  11.       try{  
  12.       validate(13);  
  13.       }catch(Exception m){System.out.println("Exception occured: "+m);}  
  14.   
  15.       System.out.println("rest of the code...");  
  16.   }  
  17. }  
Output:Exception occured: InvalidAgeException:not valid
       rest of the code...